package blog.spring.web.controller;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import blog.core.exception.FormParamErrorException;
import blog.spring.db.entity.Lable;
import blog.spring.db.service.ILableService;

@Controller
@RequestMapping("/lable")
public class LableController extends BlogController {

	public static final String CURRENT_DIR = "lable";

	public LableController() {
		super(CURRENT_DIR);
	}

	@Resource
	private ILableService lableService;

	@RequestMapping(value = { "", "*" })
	public String index(ModelMap map) {
		map.addAttribute("lables",
				lableService.findList(null, null, null, null));
		return forwardCurentIndex();
	}

	/***************** 添加标签 *****************/
	@RequestMapping(value = "/add", method = RequestMethod.GET)
	public String add(ModelMap map) {
		return forwardCurentAdd();
	}

	@RequestMapping(value = "/add", method = RequestMethod.POST)
	public String add(Lable lable, HttpServletRequest req, ModelMap map) {
		try {
			lableService.save(lable);
		} catch (FormParamErrorException e) {
			addException(map, e);
			return forwardCurentAdd();
		}
		return redirectIndex();
	}

	/***************** 修改标签 *****************/
	@RequestMapping(value = "/update/{id}", method = RequestMethod.GET)
	public String update(@PathVariable("id") int id, ModelMap map) {
		map.addAttribute("lable", lableService.findById(id));

		return forwardCurentUpdate();
	}

	@RequestMapping(value = "/update/{id}", method = RequestMethod.POST)
	public String update(@PathVariable("id") int id, Lable lable, ModelMap map,
			HttpServletRequest req) {
		try {
			lable.setLableId(id);
			lableService.update(lable);
		} catch (FormParamErrorException e) {
			addException(map, e);
			return forwardCurentUpdate();
		}
		return redirectCurentIndex();
	}

	/***************** 删除标签 *****************/
	@RequestMapping(value = "/remove/{id}", method = RequestMethod.GET)
	public String remove(@PathVariable("id") int id, ModelMap map) {
		lableService.remove(lableService.findById(id));
		return redirectCurentIndex();
	}

	/***************** 获取标签下的文章列表 *****************/
	@RequestMapping(value = "/{id}/articles", method = RequestMethod.GET)
	public String getArticles(@PathVariable("id") int id, ModelMap map) {
		map.addAttribute("articles",
				lableService.findListArticles(id, 1, 15, null, null));
		return CURRENT_DIR + "/articles";
	}
}
